<template>
  <div class="container">
    <div class="login-img">
      <img src="../../assets/ban.png" alt="" srcset="">
    </div>
    <div class="login-container">
      <div class="login-form">
        <div class="title">账号登录</div>
        <div class="splitLine"></div>
        <el-form ref="loginForm" label-position="left" :model="loginForm" label-width="80px" @submit.native.prevent>
          <el-form-item label="用户名">
            <el-input type="tel" v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input minlength="6" v-model="loginForm.password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="验证码" v-if="showCaptcha">
            <el-input placeholder="请输入验证码"  class="input-with-select" v-model="loginForm.captcha">
              <img slot="append" :src="captcha" alt="" @click="updateUuid">
            </el-input>
          </el-form-item>
          <el-button type="primary" native-type="submit" @click="onSubmit" style="width: 100%; margin-top: 20px">登录</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import uuid from '@/utils/uuid.js' // 用于生成图形验证码
import { getCaptcha, login, getInfo } from './server'

export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      }, // 登录表单数据
      rand: '', // 生成图形验证码的随机数（用uuid函数生成）
      captcha: '', // 图形验证码的图片URL
      showCaptcha: false // 时候显示图形验证码 （五次密码不正确后显示）
    }
  },
  created () {
    this.updateUuid() // 获取验证码
  },
  methods: {
    onSubmit () { // 登录
      this.loginForm.rand = this.rand // 获取随机值
      if (!this.loginForm.username || !this.loginForm.password) {
        this.$message.error('账号密码不能为空！')
        return
      }
      if (!/^[1]([3-9])[0-9]{9}$/.test(this.loginForm.username)) {
        this.$message.error('请输入合法的手机号')
        return
      }
      if (this.loginForm.password.length < 6) {
        this.$message.error('密码最少六位数')
        return
      }
      login(this.loginForm) // loginForm 参数为 username password captcha rand
        .then(res => {
          if (res.code === 'verify_faild') {
            this.$message.error('账号或者密码错误')
            return false
          }
          if (res.code && res.code === 'ok') {
            const spsToken = 'Bearer ' + res.data.token
            this.$setLocalStorage('sps_token', spsToken)
            this.$setLocalStorage('role', res.data.role)
            this.$setLocalStorage('accountId', res.data.account_id)
            this.$setLocalStorage('spId', res.data.sp_id)
            this.feachRootAccount(res.data.sp_id)
          }
          if (res.code === 'need_captcha') { // 登录失败五次后会返回 code: need_captcha，提示用户需要验证码（统一错误处理已经做提示），并将验证码显示出来
            this.showCaptcha = true
          }
        })
      this.updateUuid() // 每次登录后都刷新图形验证码
    },
    /**
     * 刷新验证码图片
     */
    updateUuid () { // 刷新验证码图片
      this.rand = uuid()
      getCaptcha({ rand: this.rand }) // 根据随机数获取验证码base64图片
        .then(res => {
          if (res.code === 'ok') {
            this.captcha = res.data
          } else {
            this.$message.error('获取验证码失败')
          }
        })
    },
    // 根据sp_id获取主账号的信息
    async feachRootAccount (id) {
      const data = {}
      const query = `?sp_id=eq.${id}`
      data.sp_id = id
      const res = await getInfo(data, query)
      if (res.code === 'ok') {
        this.$setLocalStorage('rootAccountId', res.data[0].account_id)
        this.$setLocalStorage('company_name', res.data[0].company_name)
        this.$setLocalStorage('mobile', res.data[0].mobile)
        this.$router.push({ path: '/' })
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import './index.scss'
</style>
